<!-- 录屏 -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Screen Record</title>
    <link rel="stylesheet" href="./css/01.css">
</head>
<style>
    .btns div{
      margin: 20px 30px;
      width: 100px;
      height: 40px;
      line-height: 40px;
      display: inline-block;
      background: cornflowerblue;
      border-radius: 5px;
      cursor: pointer;
      text-align: center;
      color: #fff;
      font-size: 18px;
  }
  .btns div:hover{
      background: rgb(133, 169, 235);
      color: rgb(179, 202, 236);
  }

</style>
<body>
    <canvas style="width: 400px;height:400px;"></canvas>
    <div class="btns" onclick="generateVideo(5)">
        <div id="download">download</div>
    </div>
</body>
<script>
    var video = null;
    const canvas = document.querySelector('canvas');
    const ctx = canvas.getContext('2d');
    const { width, height } = canvas;

    ctx.fillStyle = '#03a9f4';

    function draw(rotation = 0) {
        ctx.clearRect(0, 0, 1000, 1000);
        ctx.save();
        ctx.translate(width / 2, height / 2);
        ctx.rotate(rotation);
        ctx.translate(-width / 2, -height / 2);
        ctx.beginPath();
        ctx.rect(100, 100, 100, 100);
        ctx.fill();
        ctx.restore();
    }

    function update(t) {
        draw(t / 500);
        requestAnimationFrame(update);
    }
    update(0);
    var generateVideo = (duration = 10) => {
        const stream = canvas.captureStream();
        const recorder = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=h264' });
        //记录数据
        const data = [];
        recorder.ondataavailable = function (event) {
            if (event.data && event.data.size) {
                data.push(event.data);
            }
        };
        recorder.onstop = () => {
            video = URL.createObjectURL(new Blob(data, { type: 'video/mp4' }));
            startDownload(video)
        };
        recorder.start();

        setTimeout(() => {
            recorder.stop();
        }, duration * 1000);

    }
    var startDownload = () => {
        const name = new Date().toISOString().slice(0, 19).replace('T', ' ').replace(' ', '_').replace(/:/g, '-');
        const a = document.createElement('a');
        a.href = video;
        a.download = `${name}.mp4`;
        document.body.appendChild(a);
        a.click();
        video = null
    }
</script>

</html>